package com.jims.master.modules.physical.service;

import com.jims.master.common.utils.ChineseCharToEnUtils;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.modules.doctor.dao.ClinicMasterDao;
import com.jims.master.modules.doctor.dao.PatMasterIndexDao;
import com.jims.master.modules.doctor.entity.*;
import com.jims.master.modules.doctor.service.ExamApplyService;
import com.jims.master.modules.doctor.service.ExamItemService;
import com.jims.master.modules.doctor.service.LabApplyService;
import com.jims.master.modules.doctor.service.LabItemService;
import com.jims.master.modules.doctor.vo.SaveDataVo;
import com.jims.master.modules.oper.dao.ClinicItemDictDao;
import com.jims.master.modules.oper.entity.ClinicItemDict;
import com.jims.master.modules.physical.dao.TInformationDao;
import com.jims.master.modules.physical.entity.TInformation;
import com.jims.master.modules.physical.entity.TResultGroup;
import com.jims.master.modules.physical.entity.TResultOffice;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by zhangpeng on 2017/6/14.
 */
@Service
@Transactional(readOnly = true)
public class PhysicalService {

    @Autowired
    private PatMasterIndexDao patMasterIndexDao;
    @Autowired
    private ClinicMasterDao clinicMasterDao;
    @Autowired
    private TInformationDao tInformationDao;
    @Autowired
    private ClinicItemDictDao clinicItemDictDao;
    @Autowired
    private ExamApplyService examApplyService;
    @Autowired
    private ExamItemService examItemService;
    @Autowired
    private LabApplyService labApplyService;
    @Autowired
    private LabItemService labItemService;
    @Autowired
    private TResultGroupService tResultGroupService;
    @Autowired
    private TResultOfficeService tResultOfficeService;

    @Transactional(readOnly = false)
    public int savePhyUserInfo(PatMasterIndex patMasterIndex){
        int num = 0;
        if(StringUtils.isBlank(patMasterIndex.getId()) || patMasterIndex.getId() == null){
            patMasterIndex.preInsert();  
            patMasterIndex.updateOrgId();
            patMasterIndex.setInputCode(ChineseCharToEnUtils.getAllFirstLetter(patMasterIndex.getName()));
            patMasterIndexDao.insert(patMasterIndex);
            num = saveClinicMaster(patMasterIndex);
        } else {
            patMasterIndex.updateOrgId();
            patMasterIndexDao.update(patMasterIndex);
            num = saveClinicMaster(patMasterIndex);
        }
        return num;
    }

    /**
     * 体检保存就诊记录表
     * @param patMasterIndex
     * @return
     */
    @Transactional(readOnly = false)
    public int saveClinicMaster(PatMasterIndex patMasterIndex){
        int num = 0;
        Integer no= clinicMasterDao.getMaxNo(DateUtils.getDate(),patMasterIndex.getOrgId());
        if(no!=null &&!no.equals("")){
            no=no+1;
        }else{
            no=1;
        }
        ClinicMaster clinicMaster = new ClinicMaster();
        clinicMaster.preInsert();
        clinicMaster.setIsPhy("1");
        clinicMaster.setOrgId(patMasterIndex.getOrgId());
        clinicMaster.setRegistType("3");
        clinicMaster.setPatientId(patMasterIndex.getId());
        clinicMaster.setAcctDateTime(new Date());
        clinicMaster.setVisitNo(no+"");
        clinicMaster.setVisitDate(new Date());
//            clinicMaster.setRegistId("TJ");
        clinicMaster.setClinicNo(DateUtils.getDate("yyyyMMdd")+clinicMaster.getVisitNo());
        clinicMaster.setName(patMasterIndex.getName());
        clinicMaster.setSex(patMasterIndex.getSex());
        clinicMaster.setAge(patMasterIndex.getAge());
        clinicMaster.setFirstVisitIndicator(patMasterIndex.getFirstVisitIndicator());
        clinicMaster.setIdentity(patMasterIndex.getIdentity());
        clinicMaster.setChargeType(patMasterIndex.getChargeType());
        clinicMaster.setUnitInContract(patMasterIndex.getUnitInContract());
//            clinicMaster.setDeptId(clinicIndex.getDeptId());
//            clinicMaster.setDoctorId(clinicIndex.getDoctorId());
//            clinicMaster.setClinicChage(Double.valueOf(price[i]));//实收费用
        clinicMaster.setClinicType("0");

        clinicMasterDao.insert(clinicMaster);
        num = saveTinfomation(clinicMaster);
        return num;
    }

    /**
     * 保存体检信息表
     * @param clinicMaster
     * @return
     */
    @Transactional(readOnly = false)
    public int saveTinfomation(ClinicMaster clinicMaster){

        TInformation tInformation = new TInformation();
        tInformation.preInsert();
        tInformation.setOrgId(clinicMaster.getOrgId());
        tInformation.setClinicId(clinicMaster.getId());
        tInformation.setHealthexamDate(new Date());
        tInformation.setType("0"); // 普通体检
//        tInformation.setIsOk("0");
//        tInformation.setJiankangjianyi(",");
//        tInformation.setJianyi(",");
//        tInformation.setWenxintishi(",");
//        tInformation.setOrgId(",");
        int num = tInformationDao.insert(tInformation);
        return num;
    }

    @Transactional(readOnly = false)
    public int savePhyItem(OutpTreatRec outpTreatRec){
        int num = 0;
        List<OutpTreatRec> list  = new ArrayList<OutpTreatRec>();
        for(int i=0;i<outpTreatRec.getOutpTreatRecs().size();i++){
            OutpTreatRec outpTreatRec1 = outpTreatRec.getOutpTreatRecs().get(i);
            if("1".equals(outpTreatRec1.getIsNow())){
                list.add(outpTreatRec1);
            }
        }
        Map map = itemMap(list);
        List listD = (List) map.get("D");
        List listC = (List) map.get("C");
        List listE = (List) map.get("E");
        num = getDItemList(listD);
        num += getCItemList(listC);
        num += getEItemList(listE);


        return num;
    }

    private  Map itemMap(List<OutpTreatRec> list){
        Map map=new HashMap();
        itemList(map,list);
        return map;
    }

    private  void itemList(Map map,List<OutpTreatRec> list){
        if(list.size()==0){
            return;
        }
        List<OutpTreatRec> outpList=new ArrayList<OutpTreatRec>();
        List<OutpTreatRec> listLoop=new ArrayList<OutpTreatRec>();
        Boolean other=true;
        for (int i = 0; i < list.size(); i++) {
            OutpTreatRec o=new OutpTreatRec();
            o=list.get(i);
                if("C".equals(list.get(0).getItemClass()) || "D".equals(list.get(0).getItemClass())){
                    if(list.get(0).getItemClass().equals(o.getItemClass()) && list.get(0).getImplementDept().equals(o.getImplementDept())){
                        outpList.add(list.get(i));
                    }else{
                        listLoop.add(list.get(i));
                    }
                } else {
                    if(other){
                        outpList.add(list.get(i));
                        other=false;
                    }else{
                        listLoop.add(list.get(i));

                    }

                }
            }
        other=true;

        List deptList=new ArrayList();


        if("C".equals(list.get(0).getItemClass()) || "D".equals(list.get(0).getItemClass())){
            if(map.get(list.get(0).getItemClass())!=null){
                deptList=(List)map.get(list.get(0).getItemClass());
            }

            deptList.add(outpList);
            map.put(list.get(0).getItemClass(),deptList);
        } else {
            if(map.get("E")!=null){
                deptList=(List)map.get("E");
            }

            deptList.add(outpList);
            map.put("E",deptList);
        }

        itemList(map,listLoop);
    }

    public int getDItemList(List list){
        int num = 0;
        if(list!= null){
            for(int i=0;i<list.size();i++){
                num +=saveExamApplyData((List<OutpTreatRec>) list.get(i));
            }
        }

        return num;
    }


    public int getCItemList(List<OutpTreatRec> list){
        int num = 0;
        if(list!=null){
            for(int i=0;i<list.size();i++){
                num +=saveLabApplyData((List<OutpTreatRec>) list.get(i));
            }
        }

        return num;
    }
    public int getEItemList(List list){
        int num = 0;
        if (list != null) {
            for(int i=0;i<list.size();i++){
                num +=saveOutpTreatRec((List<OutpTreatRec>) list.get(i));
            }
        }

        return num;
    }


    @Transactional(readOnly = false)
    public int saveExamApplyData(List<OutpTreatRec> list){
        Integer rows = 0;
        OutpTreatRec outpTreatRec = list.get(0);
        ExamItem examItem = new ExamItem();
        ExamApply examApply =new ExamApply();
        examApply.setClinicId(outpTreatRec.getClinicId());
        examApply.setPatientId(outpTreatRec.getPatientId());
        examApply.setImplementDept(outpTreatRec.getImplementDept());
        examItem.setExamApply(examApply);
//        examItem.getExamApply().setPatientId(outpTreatRec.getPatientId());
        ExamApply examApply1=saveExamApply(examItem);
        examItem.setExamApply(examApply1);
        List<SaveDataVo> saveDataVos=saveExamItems(examItem,list);
        rows=saveDataVos.size();
        //3保存处置治疗表和代收费表
        Map<String,Object> map=examApplyService.commonSave(saveDataVos);//多条记录 对应诊疗项目

        saveTresultOffice(examApply.getClinicId(),examApply.getImplementDept(),saveDataVos);
        //更新examApplyorderssId
        examApply.setOrdersId((String) map.get("ordersId"));
        examApplyService.save(examApply);
        rows= (Integer) map.get("rows");
        return rows;
    }

    /**
     * 保存病人体检申请检查子表记录多条数据
     * @param examItem
     * @param list
     * @return
     */
    @Transactional(readOnly = false)
    private List<SaveDataVo> saveExamItems(ExamItem examItem,List<OutpTreatRec> list){
        List<SaveDataVo> resultVal=new ArrayList<SaveDataVo>();
        for(OutpTreatRec outpTreatRec:list){
            String clinicItemId = outpTreatRec.getClinicItemId();
            ClinicItemDict clinicItemDict=this.clinicItemDictDao.get(clinicItemId);
            ExamItem saveData=new ExamItem();
            saveData.setApplyId(examItem.getExamApply().getId());
            saveData.setItemName(outpTreatRec.getItemName());
            saveData.setItemCode(clinicItemDict.getItemCode());
            saveData.setClinicItemId(clinicItemDict.getId());
            saveData.setCosts(outpTreatRec.getSumPrice());
            examItemService.save(saveData);
            SaveDataVo saveDataVo=new SaveDataVo();
            saveDataVo.setPatientId(examItem.getExamApply().getPatientId());
            saveDataVo.setItemName(clinicItemDict.getItemName());
            saveDataVo.setImplementDept(outpTreatRec.getImplementDept());
            saveDataVo.setChargeFlag(examItem.getExamApply().getChargeFlag());
            saveDataVo.setConfirmFlag(examItem.getExamApply().getConfirmFlag());
            saveDataVo.setClinicId(examItem.getExamApply().getClinicId());
            saveDataVo.setNum(Integer.parseInt(outpTreatRec.getNum()));
            saveDataVo.setClinicItemId(clinicItemDict.getId());
            saveDataVo.setApplyId(examItem.getExamApply().getId());
            saveDataVo.setSumPrice(Double.valueOf(outpTreatRec.getSumPrice()));
            saveDataVo.setItemClass(clinicItemDict.getItemClass());
            saveDataVo.setIsApply("1"); // 是否申请单
            saveDataVo.setApplyNo(examItem.getExamApply().getApplyOn());
            saveDataVo.setRcptNo("");//收费号
            saveDataVo.setImplementUser("");//执行人
            saveDataVo.setInoroutFlag(examItem.getExamApply().getInoroutFlag());
            resultVal.add(saveDataVo);
        }
        return resultVal;
    }



    @Transactional(readOnly = false)
    private ExamApply saveExamApply(ExamItem examItem){
        ExamApply examApply=examItem.getExamApply();
        examApply.setApplyOn(NumberUtils.getTJClinicInspect(examApply.getClinicId()));//申请序号
        examApply.setConfirmFlag("0");//确认标志
        examApply.setChargeFlag("0");
        examApply.setBillingDept(UserUtils.getUser().getOrgDept().getId());//开单科室
        examApplyService.save(examApply);
        return examApply;
    }





    @Transactional(readOnly = false)
    public int saveLabApplyData(List<OutpTreatRec> list) {
        Integer resultVal=0;
        OutpTreatRec outpTreatRec = list.get(0);
        LabItem labItem =new LabItem();
        LabApply labApply =new LabApply();
        labApply.setClinicId(outpTreatRec.getClinicId());
        labApply.setPatientId(outpTreatRec.getPatientId());
        labApply.setImplementDept(outpTreatRec.getImplementDept());
        labItem.setLabApply(labApply);
        labItem.getLabApply().setClinicId(outpTreatRec.getClinicId());
        labItem.getLabApply().setPatientId(outpTreatRec.getPatientId());
        //1 保存检验申请主表与检验申请明细
        LabApply labApply1=saveLabApply(labItem);
        labItem.setLabApply(labApply1);
        //2 保存子表
        List<SaveDataVo> saveDataVos = saveLabItems(labItem,list);//多条记录 对应诊疗项目
        resultVal=saveDataVos.size();
            // /2 保存处置治疗|| 门诊代收费表数据
        Map<String, Object> map = this.examApplyService.commonSave(saveDataVos);
        saveTresultOffice(labApply.getClinicId(),labApply.getImplementDept(),saveDataVos);
            //3 更新ordersId
            labApply.setOrdersId((String) map.get("ordersId"));
            labApplyService.save(labApply);
            resultVal = (Integer) map.get("rows");
            return resultVal;
        }

    /**
     * 体检检验保存单表
     * @param labItem
     * @return
     */
    @Transactional(readOnly = false)
    private LabApply saveLabApply(LabItem labItem) {
        LabApply labApply=labItem.getLabApply();
        labApply.setApplyOn(NumberUtils.getTJClinicLab(labItem.getLabApply().getClinicId()));;//申请序号
        labApply.setConfirmFlag("0");
        labApply.setChargeFlag("0");
        labApply.setBillingDept(UserUtils.getUser().getOrgDept().getId());
        labApplyService.save(labApply);
        return labApply;
    }

    /**
     * 检验申请明细保存
     * @param labItem
     * @return
     */
    @Transactional(readOnly = false)
    private List<SaveDataVo> saveLabItems(LabItem labItem,List<OutpTreatRec> list) {
        List<SaveDataVo> resultVal=new ArrayList<SaveDataVo>();
        for(OutpTreatRec outpTreatRec:list){
            String clinicItemId = outpTreatRec.getClinicItemId();
            ClinicItemDict clinicItemDict=this.clinicItemDictDao.get(clinicItemId);
            LabItem saveData=new LabItem();
            saveData.setApplyId(labItem.getLabApply().getId());
            saveData.setItemName(outpTreatRec.getItemName());
            saveData.setItemCode(clinicItemDict.getItemCode());
            saveData.setClinicItemId(clinicItemDict.getId());
            saveData.setCosts(outpTreatRec.getSumPrice());
            labItemService.save(saveData);
            SaveDataVo saveDataVo=new SaveDataVo();
            saveDataVo.setPatientId(labItem.getLabApply().getPatientId());
            saveDataVo.setItemName(clinicItemDict.getItemName());
            saveDataVo.setImplementDept(outpTreatRec.getImplementDept());
            saveDataVo.setChargeFlag(labItem.getLabApply().getChargeFlag());
            saveDataVo.setConfirmFlag(labItem.getLabApply().getConfirmFlag());
            saveDataVo.setClinicId(labItem.getLabApply().getClinicId());
            saveDataVo.setNum(Integer.parseInt(outpTreatRec.getNum()));
            saveDataVo.setClinicItemId(clinicItemDict.getId());
            saveDataVo.setApplyId(labItem.getLabApply().getId());
            saveDataVo.setSumPrice(Double.valueOf(outpTreatRec.getSumPrice()));
            saveDataVo.setItemClass(clinicItemDict.getItemClass());
            saveDataVo.setIsApply("1");
            saveDataVo.setApplyNo(labItem.getLabApply().getApplyOn());
            saveDataVo.setRcptNo("");//收费号
            saveDataVo.setImplementUser("");//执行人
            saveDataVo.setInoroutFlag("0");
            resultVal.add(saveDataVo);
        }
        return resultVal;
    }


    /**
     * 保存处置治疗（体检）
     * @return
     */
    @Transactional(readOnly = false)
    public int saveOutpTreatRec(List<OutpTreatRec> outpTreatRecList) {
        int returnVal = 0;
        List<SaveDataVo> saveDataVos=new ArrayList<SaveDataVo>();
        //clinicId  patientId || performedBy num ||  clinicItemDictId
        for(OutpTreatRec outpTreatRec : outpTreatRecList){
            ClinicItemDict clinicItemDict=clinicItemDictDao.get(outpTreatRec.getClinicItemId());
            SaveDataVo saveDataVo=new SaveDataVo();
            saveDataVo.setPatientId(outpTreatRec.getPatientId());
            saveDataVo.setItemName(clinicItemDict.getItemName());
            saveDataVo.setImplementDept(outpTreatRec.getImplementDept());
            saveDataVo.setClinicItemId(outpTreatRec.getClinicItemId());
            saveDataVo.setChargeFlag("0");
            saveDataVo.setConfirmFlag("0");
            saveDataVo.setClinicId(outpTreatRec.getClinicId());
//        Integer amount=clinicVsChargeDao.findByClinicId(clinicItemDict.getId());
            saveDataVo.setNum(Integer.parseInt(outpTreatRec.getNum()));
            saveDataVo.setClinicItemId(clinicItemDict.getId());
            saveDataVo.setApplyId("");
            saveDataVo.setSumPrice(Double.valueOf(outpTreatRec.getSumPrice()));
            saveDataVo.setItemClass(clinicItemDict.getItemClass());
            saveDataVo.setIsApply("0");
            saveDataVo.setApplyNo(NumberUtils.getTJClinicTreat(outpTreatRec.getClinicId()));
            saveDataVo.setRcptNo("");//收费号
            saveDataVo.setImplementUser("");//执行人
            saveDataVo.setInoroutFlag("0");
            saveDataVos.add(saveDataVo);
            Map<String,Object> map= examApplyService.commonSave(saveDataVos);
           returnVal = map.size();
        }
        saveTresultOffice(outpTreatRecList.get(0).getClinicId(),outpTreatRecList.get(0).getImplementDept(),saveDataVos);
        return returnVal;
    }

    @Transactional(readOnly = false)
    public void saveTresultOffice(String clinicId,String deptId,List<SaveDataVo> saveDataVos){
        TResultOffice tResultOffice =new TResultOffice();
        tResultOffice.setClinicId(clinicId);
        tResultOffice.setDeptId(deptId);
        tResultOfficeService.save(tResultOffice);
        for(SaveDataVo saveDataVo:saveDataVos){
            TResultGroup tResultGroup = new TResultGroup();
            tResultGroup.setClinicId(saveDataVo.getClinicId());
            tResultGroup.setItemId(saveDataVo.getClinicItemId());
            tResultGroup.setItemName(saveDataVo.getItemName());
            tResultGroup.setOfficeId(tResultOffice.getId());
            tResultGroup.setIsOk("0");
            tResultGroup.setIsAdd("0");
            tResultGroupService.save(tResultGroup);
        }
    }

}
